package com.shizhanzhe.qdd.forward.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.kingja.loadsir.core.LoadService;
import com.shizhanzhe.qdd.R;
import com.shizhanzhe.qdd.base.BaseActivity;
import com.shizhanzhe.qdd.base.UserBean;
import com.shizhanzhe.qdd.forward.adapter.WebRecyclerAdapter;
import com.shizhanzhe.qdd.forward.bean.ShareDetail;
import com.shizhanzhe.qdd.forward.dialog.SharePopWindow;
import com.shizhanzhe.qdd.home.dialog.ExitDialog;
import com.shizhanzhe.qdd.url.Path;
import com.shizhanzhe.qdd.utils.BitMap;
import com.shizhanzhe.qdd.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.qdd.utils.Util;
import com.shizhanzhe.qdd.utils.a;
import com.shizhanzhe.qdd.widget.ErrorCallback;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by zz9527 on 2018/10/19.
 */
public class WebActivity extends BaseActivity {
    private WebView web;
    private TextView price;
    private RecyclerView rv;
    private WebRecyclerAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).statusBarColor(R.color.them).fitsSystemWindows(true).init();

//                popWindow.showAtLocation(web, Gravity.BOTTOM, 0, 0);
//                popWindow.setListener(new SharePopWindow.ShareListener() {
//                    @Override
//                    public void shareFriend() {
//                        send(WebActivity.this, 0, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid), title, desc);
//                    }
//
//                    @Override
//                    public void shareCircle() {
//                        send(WebActivity.this, 1, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid), title, desc);
//                    }
//
//                    @Override
//                    public void shareQQ() {
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        Uri content_url = Uri.parse(Path.SHAREURL(ym, getIntent().getIntExtra("id", 0), UserBean.uid, 4));
//                        intent.setData(content_url);
//                        intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
//                        startActivity(intent);
//                    }
//
//                    @Override
//                    public void shareQQKJ() {
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        Uri content_url = Uri.parse(Path.SHAREURL(ym, getIntent().getIntExtra("id", 0), UserBean.uid, 5));
//                        intent.setData(content_url);
//                        intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
//                        startActivity(intent);
//                    }
//
//                    @Override
//                    public void shareWB() {
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        Uri content_url = Uri.parse(Path.SHAREURL(ym, getIntent().getIntExtra("id", 0), UserBean.uid, 1));
//                        intent.setData(content_url);
//                        intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
//                        startActivity(intent);
//                    }
//                });
//
//            }
//        });


    }

    @Override
    protected int getLayout() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView() {
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });

        web = findViewById(R.id.web);
        final ProgressBar pg1 = findViewById(R.id.progressBar);
        web.setBackgroundColor(0);
        web.getSettings().setJavaScriptEnabled(true);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);
        //设置webview显示屏幕宽度 不能滑动
//        web.getSettings().setUseWideViewPort(true);
//        web.getSettings().setLoadWithOverviewMode(true);
        // 可以使用插件
        web.getSettings().setPluginState(WebSettings.PluginState.ON);
//        web.getSettings().setBuiltInZoomControls(true);//缩放
//        web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局

        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                if (newProgress == 100) {
                    //加载完网页进度条消失
                    pg1.setVisibility(View.INVISIBLE);
                } else {
                    //开始加载网页时显示进度条
                    pg1.setVisibility(View.VISIBLE);
                    //设置进度值
                    pg1.setProgress(newProgress);
                }
            }
        });
        web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        findViewById(R.id.wxq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send(WebActivity.this, 0, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid), title, desc);
            }
        });
        findViewById(R.id.wxpyq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send(WebActivity.this, 1, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid), title, desc);
            }
        });
        price = findViewById(R.id.price);
        rv = findViewById(R.id.rv);
        rv.setFocusable(false);
        rv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new WebRecyclerAdapter(WebActivity.this);
        rv.setAdapter(adapter);
        rv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
//        findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                SharePopWindow popWindow = new SharePopWindow(WebActivity.this);
        if (Util.isInstallApp(WebActivity.this, "com.tencent.mobileqq")) {
            appid = "weixin://sendreq?appid=wxf0a80d0ac2e82aa7";
            appname = "com.tencent.mobileqq";
        } else if (Util.isInstallApp(WebActivity.this, "com.tencent.mtt")) {
            appid = "weixin://sendreq?appid=wx64f9cf5b17af074d";
            appname = "com.tencent.mtt";
        } else if (Util.isInstallApp(WebActivity.this, "com.ss.android.article.news")) {
            appid = "weixin://sendreq?appid=wx50d801314d9eb858";
            appname = "com.ss.android.article.news";
        } else {
            final ExitDialog mdelDialog = new ExitDialog(WebActivity.this);
            mdelDialog.setExitListener(new ExitDialog.ExitListener() {
                @Override
                public void chooseTrue() {
                    //确定清除
                    mdelDialog.dismiss();
                    Uri content_url = Uri.parse("http://migmkt.qq.com/qbrowser/newindex_22060.html");
                    startActivity(new Intent(Intent.ACTION_VIEW, content_url));
                }

                @Override
                public void chooseFalse() {
                    //取消
                    mdelDialog.dismiss();
                }
            });
            mdelDialog.show();
            mdelDialog.downQQ();
            return;
        }
    }

    String title = "";
    String desc = "";
    Bitmap bm = null;
    private int artid = 0;

    @Override
    protected void getData() {
        getYM();
        OkHttpDownloadJsonUtil.downloadJson(this, Path.SHAREDETAIL(getIntent().getIntExtra("id", 0), UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    Gson gson = new Gson();
                    final ShareDetail shareDetail = gson.fromJson(json, ShareDetail.class);
                    title = shareDetail.getData().getAname();
                    artid = shareDetail.getData().getArtid();
                    price.setText(shareDetail.getData().getPrice() + "");
                    desc = title;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            bm = BitMap.getHtmlByteArray(Path.img(shareDetail.getData().getIcon()));
                        }
                    }).start();
                    if (shareDetail.getData().getIsshow() == 0) {
                        String artcontent = shareDetail.getData().getArtcontent();
//                        String htmlModify = artcontent.replaceAll("<br/>", "");
//                        String htmlcontent = cssLayout + "<body><div id='webview_content_wrapper'>" + htmlModify + "</div></body>";
//                        Log.i("_________",htmlcontent);
                        web.loadDataWithBaseURL(null, artcontent, "text/html", "utf-8", null);
                    } else {
                        web.loadUrl(shareDetail.getData().getUrl());
                    }
                    adapter.updateData(1, shareDetail.getRetui());
                    adapter.setOnItemClickListener(new WebRecyclerAdapter.ItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            startActivity(new Intent(WebActivity.this, WebActivity.class).putExtra("id", shareDetail.getRetui().get(position).getArtid()));
                        }
                    });
                    loadService.showSuccess();
                } catch (Exception e) {
                    loadService.showCallback(ErrorCallback.class);
                }
            }
        });
    }

    String ym = "";

    private void getYM() {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.BASE_URL + "/index.php/index/index/domain", new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    ym = object.optString("domain");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }


    IWXAPI iwxapi;
    String appid = "";
    String appname = "";

    public void send(Context paramContext, int paramInt, String url, String title, String desc) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        iwxapi = WXAPIFactory.createWXAPI(paramContext, "wx597d8e43a8463f61", true);
        // 将应用的appId注册到微信
        iwxapi.registerApp("wx597d8e43a8463f61");
        WXWebpageObject localWXWebpageObject = new WXWebpageObject();
        localWXWebpageObject.webpageUrl = url;
        WXMediaMessage wxMediaMessage = new WXMediaMessage(localWXWebpageObject);
        wxMediaMessage.title = title;
        wxMediaMessage.description = desc;
        if (bm != null) {
            wxMediaMessage.thumbData = Util.bmpToByteArray(Bitmap.createScaledBitmap(bm, 150, 150, true), true);
        } else {
            wxMediaMessage.thumbData = Util.bmpToByteArray(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.logo), 150, 150, true), true);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = wxMediaMessage;
        req.scene = paramInt;
        iwxapi.sendReq(req);
        Bundle bundle = new Bundle();
        req.toBundle(bundle);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClassName("com.tencent.mm", "com.tencent.mm.plugin.base.stub.WXEntryActivity");
        intent.putExtra("_mmessage_sdkVersion", 620824064);
        intent.putExtra("_mmessage_appPackage", appname);
        intent.putExtra("_mmessage_content", appid);
        intent.putExtra("_mmessage_checksum", a.a(appid, 620824064, "com.shizhanzhe.qdd"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        paramContext.startActivity(intent);
        OkHttpDownloadJsonUtil.downloadJson(this, Path.SHARERECORD(artid, UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {

            }
        });
    }

    private static String buildTransaction(String paramString) {
        if (paramString == null) {
        }
        for (paramString = String.valueOf(System.currentTimeMillis()); ; paramString = paramString + System.currentTimeMillis()) {
            return paramString;
        }
    }
}
